# -*- coding: utf-8 -*-
import urllib,re,sys,logging
sys.path.insert(0,'weibopy.zip')
sys.path.append('weibopy.zip/weibopy')
from datetime import  datetime

import ConfigParser
from google.appengine.api import xmpp
from google.appengine.ext import webapp,db
from google.appengine.ext.webapp.util import run_wsgi_app

import WeiboActions
import WeiboAuth
import RegModel

class XMPPHandler(webapp.RequestHandler):
    def __init__(self, *args, **kwargs):
        super(XMPPHandler, self).__init__(*args, **kwargs)
        self.auth = WeiboAuth.WeiboAuth()
        self.action = WeiboActions.WeiboActions()

    def post(self):
        message = xmpp.Message(self.request.POST)
        self.auth.sender =  message.sender.split('/')[0]
        msg = message.body
        command = msg[0]
        body = msg[1:].strip()

        if command=='r':
            message.reply(u"你好，" + self.auth.sender + u"！请访问以下地址并记录密钥，以便给予应用授权"
                          +  r"http://talkgtalk.sinaapp.com/")
        if command=='a':
            self.auth.store_auth(self.auth.sender,body)
            message.reply(u"机器人可以工作了！")
#       私信功能尚未开放
#        if command=='l':
#            message.reply('In command l!')
#            id,content = body.split()
#            retval = self.action.private_letter_weibo(content,self.auth.sender,id)
#            if retval is not None:
#                message.reply(u"私信发送成功："+ retval)
#            else:
#                message.reply(u"私信发送失败！请重新注册！")
        if command=='w':
            message.reply('In command w!')
            retval = self.action.publish_sina_weibo(body,self.auth.sender)
            if retval is not None:
                message.reply(u" 微博发布成功！")
            else:
                message.reply(u"微博发布失败！请重新注册！")
        if command=='q':
            message.reply('In command q!')
            query = RegModel.get_RegModel(self.auth.sender)
            #ancestor = RegModel.RegModel.get_by_key_name(self.auth.sender)
            #query = db.Query(ancestor).get()
            if query is not None:
                message.reply(u"注册ID："+ query.uid + u"注册Token：" + query.token)
            else:
                message.reply(self.auth.sender+ u"尚未注册！")

application = webapp.WSGIApplication([('/_ah/xmpp/message/chat/', XMPPHandler)],
    debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()